package fortunata.jspwikiplugins.omemo;

import com.ecyrd.jspwiki.plugin.WikiPlugin;
import com.ecyrd.jspwiki.plugin.PluginException;
import com.ecyrd.jspwiki.WikiContext;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.datatypes.xsd.XSDDateTime;

import java.util.Map;
import java.util.Calendar;

import fortunata.fswapps.omemo.OntologyWikiPageName;
import fortunata.util.NiceDate;
import fortunata.FortunataPlugin;
import fortunata.fswapps.omemo.Omemo;
import org.apache.log4j.Logger;

/**
 * This plugin creates an ordenable wiki list (table) with all the ontologies stored in OMEMO
 * Information comes from ontologic (OWL) files.
 */
public class GenerateWikiPageContent extends FortunataPlugin implements WikiPlugin {
    private static Logger log = Logger.getLogger( GenerateWikiPageContent.class );
    private Omemo omemo;
    
    public String execute (WikiContext context, Map parameterMap) throws PluginException{
        omemo = new Omemo();
        try {
            //Ensure definitions file exists
            omemo.createDataModelFileIfNeeded(context);
            //Ensure individuals file exists
            omemo.createIndividualsFileIfNeeded(context);

            //Creates an empty model
            OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RDFS_INF, null);
            //Reads Omemo Ontology
            omemo.readSWAppModel(m, context);

            //Write info in the wiki page
            String wikiText = writeWikiPage(m, context);
            return renderWikiText(context, wikiText);
        }catch(PluginException e){
            //Shows a nice red alert with the message.
             throw new PluginException(renderWikiText(context, e.getMessage()));
        }
    }

    /**
     * Writes the string returned.
     * @param m
     * @param context
     * @return  wiki text
     * @throws PluginException
     */
    private String writeWikiPage(OntModel m, WikiContext context) throws PluginException{
        StringBuffer sb = new StringBuffer();
        String URI = omemo.getURI();
        
        sb.append("%%sortable" + nl);
        sb.append("||Wiki Page||URL(where ontology comes from)||Onto Lang||Version||Last check" +  nl);
        String uriClass = URI + omemo.getMainClassName();
        Property propURL = m.getProperty(URI + Omemo.propNameUrl);
        Property propAlias = m.getProperty(URI + Omemo.propNameAlias);
        Property propOntoLang = m.getProperty(URI + Omemo.propNameOntoLang);
        Property propVersion = m.getProperty(URI + Omemo.propNameVersion);
        Property propLastCheck = m.getProperty(URI + Omemo.propNameLastCheck);
        Resource res = m.getResource(uriClass);
        ExtendedIterator iter = m.listIndividuals(res);
        while (iter.hasNext()){
            Individual indiv = (Individual) iter.next();
            OntologyWikiPageName owpn = new OntologyWikiPageName(indiv.getPropertyValue(propAlias).toString().toUpperCase(),
                                                             indiv.getPropertyValue(propVersion).toString());
            //String rdfFileNameWithPath = FormManager.getWorkDir(context) + File.separator + owpn.toFileName();
            //String checkString = AddOnto.checkUpdates(rdfFileNameWithPath, indiv.getPropertyValue(propURL).toString());

            sb.append("|[" + owpn + "]");
            sb.append("|[" + indiv.getPropertyValue(propURL) +"]");
            sb.append("|" + indiv.getPropertyValue(propOntoLang));
            sb.append("|" + indiv.getPropertyValue(propVersion));
            RDFNode n = indiv.getPropertyValue(propLastCheck);
            Literal l =  (Literal)(n.as(Literal.class)); //An RDFNode can be a Resource or a Literal
            Calendar c = ((XSDDateTime) l.getValue()).asCalendar();
            sb.append("|" + NiceDate.niceDateIntervalTillNow(c.getTime()));
            sb.append(wnl);
        }
        sb.append("%%");
        return sb.toString();






//        return   "<TR>" +
//                     "<TD>"+ owpn.toFileName() + "<BR> ("+ checkString + ")"+ "</TD>"+
//                     "<TD><A href='"+link+"'>"+ontologyWikiPageName +"</A></TD>"+
//                     "<TD><A href='"+altURL+"'>"+altURL+"</A></TD>"+
//                     "<TD>"+ ns +"</TD>"+
//                     "<TD>"+ ontLang +"</TD>"+
//                 "</TR>";
    }

}